<template>
    <view class="order">
        <swiper
            class="swiper" 
            circular
            indicator-dots
            autoplay
        >
            <swiper-item
                v-for="(item, index) in formData.zsg_ex6?.split(',')"
                :key="'0-' + index"
            >
                <image 
                    :src="item" 
                    :draggable="false"
                    mode="scaleToFill"
                    class="swiper-img"
                ></image>
            </swiper-item>
        </swiper>
        <view class="msg1-box">
            <view class="msg1">
                <view class="msg1-price">
                    <view class="msg1-price-text-1">
                        积分兑换
                    </view>
                    <view class="msg1-price-text-2">
                        {{ Number(formData.zsg_ex2).toFixed(2) }}积分
                    </view>
                </view>
                <view class="msg1-num">
                    已兑换{{ formData.zsg_ex4 }}件
                </view>
            </view>
            <view class="title">
                {{ formData.zsg_ex1 }} {{ formData.zsg_ex10 }}
            </view>
        </view>
        <view class="msg2-box">
            <view 
                v-if="formData.zsg_ex12"
                class="msg2-content-1"
            >
                <view class="msg2-content-1-color">产地信息：</view>
                <view>{{ formData.zsg_ex12 }}</view>
            </view>
            <view class="msg2-content-1">
                <view class="msg2-content-1-color">运费金额：</view>
                <view>商家包邮费</view>
            </view>
            <view 
                class="msg2-content-1"
                @click="callPhone"
            >
                <view class="msg2-content-1-color">客服电话：</view>
                <view>0571-87551689</view>
                <view class="iconfont icon-kefuzhongxin msg2-content-1-icon"></view>
            </view>
            <view class="msg2-content-1">
                <view class="msg2-content-1-color">客服时间：</view>
                <view>周一至周日09:00-22:00</view>
            </view>
            <view class="msg2-content-1">
                <view class="msg2-content-1-color">发货时间：</view>
                <view>预计1-7天内发货</view>
            </view>
        </view>
        <!-- <view class="specifications">
            {{ formData.zsg_ex10 }}
        </view> -->
        <view class="desc">
            {{ formData.zsg_ex5 }}
        </view>
        <view class="text-1-box">
            商品详情
        </view>
        <image
            v-for="(item, index) in formData.zsg_ex11?.split(',')"
            :key="'1-' + index"
            :src="item"
            :draggable="false"
            mode="widthFix"
            style="width: 100vw;"
        />
        <view class="goods-carts">
            <uni-goods-nav
                :fill="true"  
                :options="options" 
                :buttonGroup="buttonGroup"  
                style="position: fixed; left: 0; right: 0; bottom: 0;"
                @click="onClick" 
                @buttonClick="buttonClick" 
            />
        </view>    
        <!-- <uni-popup
            ref="popup1" 
            type="bottom"
            :is-mask-click="true"
        >
            <view class="my-popup1-box">
                <view class="my-popup1-main-1">
                    <image
                        :src="formData.zsg_ex6?.split(',')[0]" 
                        :draggable="false"
                        mode="scaleToFill"
                        class="my-popup1-main-1-img"
                    ></image>
                    <view class="my-popup1-main-1-text">
                        <view class="my-popup1-main-1-text-1">{{ formData.zsg_ex1 }} {{ formData.zsg_ex10 }}</view>
                        <view class="my-popup1-main-1-text-3">
                            <view class="my-popup1-main-1-text-3-right">
                                {{ Number(formData.zsg_ex2).toFixed(2) }}积分
                            </view>
                            <uni-number-box
                                v-model="formData.commodityNum"
                                :min="1"
                                @change="commodityNumChange"
                            ></uni-number-box>
                        </view>
                    </view>
                </view>
                <view 
                    v-for="(item1, index1) in formData.commoditySpec"
                    :key="'2-' + index1"
                    class="my-popup1-main-2"
                >
                     <view class="my-popup1-main-2-title-1">{{ item1[0].zsas_ex1}}</view>
                     <view 
                        
                        class="my-popup1-main-2-text-1"
                    >
                        <view 
                            v-for="(item2, index2) in item1"
                            :key="'3-' + index2"
                            class="my-popup1-main-2-text-2"
                        >
                            {{ item2.zsgs_ex2 }}
                        </view>
                    </view>
                </view> 
                <view class="my-popup1-button">
                    <button
                        :class="['my-popup1-button-default-btn']"
                        style="position: fixed; left: 0; right: 0; bottom: 0; border-radius: 0;"
                        @click="onSubmit" 
                        
                    >
                        下一步
                    </button>
                </view>
            </view>
        </uni-popup> -->
        
        <vk-data-goods-sku-popup
            ref="skuPopup"
            v-model="skuKey"
            border-radius="20"
            :z-index="990"
            :localdata="goodsInfo"
            :mode="skuMode"
            :amount-type="0"
            @open="onOpenSkuPopup"
            @close="onCloseSkuPopup"
            @add-cart="addCart"
            @buy-now="buyNow"
        ></vk-data-goods-sku-popup>
        
        <uni-popup
            ref="popup2" 
            type="bottom"
            :is-mask-click="true"
        >
            <view class="my-popup1-box">
                <view class="my-popup1-main-1">
                    <image
                        :src="formData.zsg_ex6?.split(',')[0]" 
                        :draggable="false"
                        mode="scaleToFill"
                        class="my-popup1-main-1-img"
                    ></image>
                    <view class="my-popup1-main-1-text">
                        <view class="my-popup1-main-1-text-1">{{ formData.zsg_ex1 }} {{ formData.zsg_ex10 }}</view>
                        <view class="my-popup1-main-1-text-3">
                            <view class="my-popup1-main-1-text-3-right">
                                {{ Number(formData.zsg_ex2).toFixed(2) }}积分
                            </view>
                            <uni-number-box
                                v-model="formData.commodityNum"
                                :min="1"
                                @change="commodityNumChange"
                            ></uni-number-box>
                        </view>
                    </view>
                </view>
                <view class="my-popup1-main-2">
                    <view class="my-popup1-main-2-title-1">型号</view>
                    <view class="my-popup1-main-2-text-1">{{ formData.zsg_ex10 }}</view>
               </view> 
                <view class="my-popup1-button">
                    <button
                        :class="['my-popup1-button-default-btn']"
                        style="position: fixed; left: 0; right: 0; bottom: 0; border-radius: 0;"
                        @click="addToCart(formData.commodityNum)" 
                        
                    >
                        加入购物车
                    </button>
                </view>
            </view>
        </uni-popup>
    </view>
</template>

<script lang="ts" setup>
    import { onLoad, onShow, onHide, onReady, onUnload, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
    import { markRaw, reactive, ref } from 'vue'
    import type { Ref, Raw } from 'vue'
    import { getGoodsSpecApi } from '@/apis'
    const popup1: Ref<any> = ref(null)
    const popup2: Ref<any> = ref(null)
    // popup1.value.close()
    const formData: Ref<any> = ref({
        commodityNum: 1,
        commoditySpec: [],
        
        // zsg_ex1: '12瓶装易捷水', //商品名称
        // zsg_ex2: 120, //售价积分
        // zsg_ex4: 62, //销售量
        // zsg_id: 100,
        // zsg_ex6: 'http://oss3.smartyoke.com/putaway/23e338cee2cb4428b7a29f45e4ff0268.jpg', //商品图片
        // zsg_ex3: 0, //库存数量
        // zsg_ex5: '商品简介', //商品简介
        // zsg_ex7: '商品类型名称', //商品类型名称
        // zsg_ex8: '已上架', //是否上架:未上架 ,已上架
        // zsg_ex9: '未审核', //审核状态:未审核 ,已审核
        // zsg_create_time: '', //创建时间
        // zsg_dj_ex3: 0, //冻结数量
        
    })
    const options: Ref<any[]> = ref([
  //       {
		// 	icon: 'headphones',
		// 	text: '客服'
		// }, {
		// 	icon: 'shop',
		// 	text: '店铺',
		// 	info: 2, //右上角数字角标
		// 	infoBackgroundColor:'#007aff', //角标背景色
		// 	infoColor:"red" //角标前景色
		// }, 
        {
			icon: 'cart',
			text: '购物车',
			info: 0
		}
    ])
    const buttonGroup: Ref<any[]> = ref([
        {
          text: '加入购物车',
          backgroundColor: 'linear-gradient(90deg, #4bbaff, #088FEB)',
          color: '#fff'
        },
        {
          text: '立即兑换',
          // backgroundColor: '#46c1ff',
          backgroundColor: 'linear-gradient(90deg, #1E83FF, #0053B8)',
          color: '#fff'
        }
    ])
    
    onLoad((val: any) => {
        console.log(val)
        
        formData.value = { ...formData.value, ...JSON.parse(uni.getStorageSync('productDetails'))}
        
        getGoodsSpecApi({
            zsgm_id: '1'
        }).then((res: any) => {
            let goodsTypeArr: any[] = []
            let goodsArr: any[] = []
            res.data.forEach((item1: any, index1: number) => {
                let idxof = goodsTypeArr.indexOf(item1.zsas_ex1)
                if ( idxof != -1) {
                    goodsArr[idxof].push(item1)
                } else {
                    goodsTypeArr.push(item1.zsas_ex1)
                    goodsArr.push([item1])
                }
            })
            formData.value.commoditySpec = goodsArr
        })
        
    })
    onShow(() => {
        console.log(uni.getStorageSync('shopingCartArr'))
        options.value[0].info = 0
        if (uni.getStorageSync('shopingCartArr')) {
            JSON.parse(uni.getStorageSync('shopingCartArr')).forEach((item, index) => {
                options.value[0].info += item.commodityNum
            })
        }
    })
    
    const onClick = (e) => {
        uni.navigateTo({
            url: '/pages/shoppingCart/shoppingCart'
        })
    }
    const buttonClick = (e) => {
        console.log(e)
        if (e.content.text == '加入购物车') {
            popup2.value.open()
        } else if (e.content.text == '立即兑换') {
            // popup1.value.open()
            openSkuPopup()
        }
    }
    const onSubmit = () => {
        popup1.value.close()
        uni.setStorageSync('commoditiesClearingArr', JSON.stringify([formData.value]))
        uni.navigateTo({
            url: '/pages/commoditiesClearing/commoditiesClearing'
        })
        // uni.showModal({
        //     showCancel: true,
        //     title: '温馨提示',
        //     content: '是否确定兑换？',
        //     success: function (res3) {
        //         // 调接口
        //         uni.redirectTo({
        //             url: '/pages/mallOrders/mallOrders'
        //         });
        //         // uni.switchTab({
        //         // 	url: '/pages/mallOrders/mallOrders'
        //         // });
        //         // if (res3.confirm) {
        //         // 	console.log('用户点击确定');
        //         // } else if (res3.cancel) {
        //         // 	console.log('用户点击取消');
        //         // }
        //     }
        // });
    }
    const addToCart = (num: number) => {
        console.log(options.value)
        options.value[0].info += num
        if (uni.getStorageSync('shopingCartArr')) {
            uni.setStorageSync('shopingCartArr', JSON.stringify([...JSON.parse(uni.getStorageSync('shopingCartArr')), formData.value]))
        } else {
            uni.setStorageSync('shopingCartArr', JSON.stringify([formData.value]))
        }
        popup2.value.close()
    }
    const commodityNumChange = (val: any) => {
        console.log(val)
    }
    const callPhone = () => {
        uni.makePhoneCall({
        	phoneNumber: '057187551689',
            success: () => {
                console.log('成功')
            },
            fail: () => {
                console.log('失败')
            },
            complete: () => {
                console.log('一定走')
            }
        })
    }
    
    const skuKey: Ref<boolean> = ref(false) // 是否打开SKU弹窗
    const skuMode: Ref<number> = ref(3) // SKU弹窗模式 1:都显示 2:只显示购物车 3:只显示立即购买
    const goodsInfo: Ref<any> = ref({}) // 后端返回的商品信息
    // 获取商品信息，并打开sku弹出
    const openSkuPopup = () => {
        /**
         * 获取商品信息
         * 这里可以看到每次打开SKU都会去重新请求商品信息,为的是每次打开SKU组件可以实时看到剩余库存
         */
        // 此处写接口请求，并将返回的数据进行处理成goodsInfo的数据格式，
        // goodsInfo是后端返回的数据
        goodsInfo.value = {
            "_id": "001",
            "name": "iphone11",
            "goods_thumb": "https://img14.360buyimg.com/n0/jfs/t1/59022/28/10293/141808/5d78088fEf6e7862d/68836f52ffaaad96.jpg",
            "sku_list": [
                {
                    "_id": "001",
                    "goods_id": "001",
                    "goods_name": "iphone11",
                    "image": "https://img14.360buyimg.com/n0/jfs/t1/79668/22/9987/159271/5d780915Ebf9bf3f4/6a1b2703a9ed8737.jpg",
                    "price": 19800,
                    "sku_name_arr": ["红色", "128G", "公开版"],
                    "stock": 1000
                },
                {
                    "_id": "002",
                    "goods_id": "001",
                    "goods_name": "iphone11",
                    "image": "https://img14.360buyimg.com/n0/jfs/t1/52252/35/10516/124064/5d7808e0E46202391/7100f3733a1c1f00.jpg",
                    "price": 9800,
                    "sku_name_arr": ["白色", "256G", "公开版"],
                    "stock": 100
                },
                {
                    "_id": "003",
                    "goods_id": "001",
                    "goods_name": "iphone11",
                    "image": "https://img14.360buyimg.com/n0/jfs/t1/79668/22/9987/159271/5d780915Ebf9bf3f4/6a1b2703a9ed8737.jpg",
                    "price": 19800,
                    "sku_name_arr": ["红色", "256G", "公开版"],
                    "stock": 1
                }
            ],
            "spec_list": [
                {
                    "name": "颜色",
                    "list": [
                        { "name": "红色" },
                        { "name": "黑色" },
                        { "name": "白色" }
                    ]
                },
                {
                    "name": "内存",
                    "list": [
                        { "name": "128G" },
                        { "name": "256G" }
                    ],
                },
                {
                    "name": "版本",
                    "list": [
                        { "name": "公开版" },
                        { "name": "非公开版" }
                    ]
                }
            ]
        };
        skuKey.value = true;
    }
    // sku组件 开始-----------------------------------------------------------
    const onOpenSkuPopup = () => {
        console.log("监听 - 打开sku组件");
    }
    const onCloseSkuPopup = () => {
        console.log("监听 - 关闭sku组件");
    }
    // 加入购物车前的判断
    const addCartFn = (obj) => {
        let { selectShop } = obj;
        // 模拟添加到购物车,请替换成你自己的添加到购物车逻辑
        let res = {};
        let name = selectShop.goods_name;
        if (selectShop.sku_name != "默认") {
            name += "-" + selectShop.sku_name_arr;
        }
        res.msg = `${name} 已添加到购物车`;
        if (typeof obj.success == "function") obj.success(res);
    }
    // 加入购物车按钮
    const addCart = (selectShop) => {
        console.log("监听 - 加入购物车");
        addCartFn({
            selectShop: selectShop,
            success: res => {
                // 实际业务时,请替换自己的加入购物车逻辑
                uni.showToast({
                    title: res.msg,
                    icon: "none"
                });
                setTimeout(() => {
                    skuKey.value = false;
                }, 300);
            }
        });
    }
    // 立即购买
    const buyNow = (selectShop) => {
        console.log("监听 - 立即购买");
        addCartFn({
            selectShop: selectShop,
            success: res => {
                // 实际业务时,请替换自己的立即购买逻辑
                uni.showToast({
                    title: '立即购买',
                    icon: "none"
                });
            }
        });
    }
</script>

<style lang="scss" scoped>
    .order {
        min-height: 100vh;
        background-color: #f2f2f2;
    }
    .swiper {
        height: 680rpx;
        box-sizing: border-box;
        // padding: 10rpx;
        // border-radius: 20rpx;
    }
    .swiper-img {
        width: 100%;
        height: 100%
    }
    .msg1-box {
        background: #fff;
        padding: 30rpx 20rpx;
        .msg1 {
            // height: 100rpx;
            // background: linear-gradient(to bottom, #46c1ff, #e2e2e2);
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-sizing: border-box;
            // padding: 0 10rpx;
            .msg1-price {
                display: flex;
                align-items: center;
                .msg1-price-text-1 {
                    height: 45rpx;
                    background: #f2403c;
                    box-sizing: border-box;
                    padding: 5rpx;
                    border-radius: 10rpx;
                    font-size: 24rpx;
                    color: #fff;
                }
                .msg1-price-text-2 {
                   font-size: 40rpx;
                   // font-weight: bold;
                   color: red;
                   padding-left: 10rpx;
                }
            }
            .msg1-num {
                font-size: 30rpx;
                // color: #fff;
                color: #c0c1c3;
            }
        }
        .title {
            font-size: 32rpx;
            // font-weight: bold;
            box-sizing: border-box;
            // padding: 10rpx;
            letter-spacing: 1rpx;
            padding-top: 20rpx;
        }
    }
    .msg2-box {
        margin-top: 20rpx;
        box-sizing: border-box;
        padding: 20rpx 20rpx;
        border-radius: 20rpx;
        background: #fff;
        font-size: 28rpx;
        .msg2-content-1 {
            display: flex;
            padding: 10rpx 0;
            .msg2-content-1-color {
                color: rgb(183,184,191);
            }
            .msg2-content-1-icon {
                margin-left: 10rpx;
                color: #023e9e;
                font-size: 36rpx;
            }
        }
    }
    .specifications {
        font-size: 30rpx;
        font-weight: bold;
        box-sizing: border-box;
        padding: 10rpx;
        letter-spacing: 1rpx;
    }
    .desc {
        margin-top: 20rpx;
        box-sizing: border-box;
        border-radius: 20rpx;
        padding: 20rpx;
        line-height: 40rpx;
        background: #fff;
        font-size: 28rpx;
        text-indent: 56rpx;
        letter-spacing: 1rpx;
        color: #505050;
    }
    .text-1-box {
        text-align: center;
        padding: 20rpx 0;
    }
    .goods-carts {
        height: 110rpx;
        :deep(.uni-tab__cart-box) {
            height: 110rpx;
        }
    }
    .my-popup1-box {
        // background: #f2f2f2;
        background: #fff;
        // width: 600rpx; 
        box-sizing: border-box; 
        font-size: 28rpx;
        // padding: 0 0 30rpx 0; 
        // border-radius: 50rpx 50rpx 0rpx 0rpx;
        .my-popup1-header {
            display: flex;
            // justify-content: space-between;
            align-items: center;
            height: 100rpx;
            background: #fff;
            .my-popup1-header-main {
                flex: 1;
                padding: 0 10rpx;
                font-size: 26rpx
            }
            .my-popup1-header-icon-img {
                width: 50rpx;
                height: 50rpx
            }
            
        }
        
        .my-popup1-main-1 {
            // background: #fff;
            display: flex;
            // margin-top: 20rpx;
            box-sizing: border-box;
            padding: 20rpx 20rpx;
            .my-popup1-main-1-img {
                width: 180rpx;
                height: 180rpx;
                box-sizing: border-box;
                border-radius: 10rpx;
            }
            .my-popup1-main-1-text {
                flex: 1;
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                box-sizing: border-box;
                padding-left: 10rpx;
                .my-popup1-main-1-text-1 {
                    height: 80rpx;
                    overflow: hidden;
                }
                .my-popup1-main-1-text-3 {
                    display: flex;
                    justify-content: space-between;
                    .my-popup1-main-1-text-3-right {
                       // text-align: right;
                       color: #f2403c;
                       // font-weight: bold;
                       // padding-left: 10rpx;
                    }
                }
            }
        }
        .my-popup1-main-2 {
            box-sizing: border-box;
            padding: 20rpx 20rpx;
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            // font-size: 28rpx;
            .my-popup1-main-2-title-1 {
                padding-bottom: 20rpx;
            }
            .my-popup1-main-2-text-1 {
                display: flex;
                .my-popup1-main-2-text-2 {
                    box-sizing: border-box;
                    text-align: center;
                    padding: 10rpx;
                    margin: 10rpx;
                    background: #dae4f2;
                }
            }
        }
        .my-popup1-button {
            background-color: #fff;
            height: 110rpx;
            .my-popup1-button-disabled-btn {
                background-color: rgba(41, 121, 255, 0.6) !important;
                color: #fff9f9 !important;
            }
            .my-popup1-button-default-btn {
                background-color: #2979ff !important;
                color: #fff !important;
                font-size: 28rpx;
                padding: 15rpx 0;
            }
        }
    }
    
</style>
